<?php

use app\common\model\FosterOrder;
use app\common\model\FosterOrderExtra;
use app\common\model\JlLog;
use app\common\model\JlLqLog;
use app\common\model\Order;
use app\common\model\Recharge;
use app\common\model\UserLevel;
use app\common\model\UserRechargeLog;
use app\common\model\Users;
use app\common\model\UserWallet;
use app\common\model\UserWalletDeal;
use think\facade\Db;
// 应用公共文件
function encrypt($str){
    return md5("ZHANGDADA".$str);
}
/**
 * @param string $dir 删除目录
 */
function delDir($dir){
    if (!is_dir($dir)){
        return false;
    }
    $files=scandir($dir);
    foreach ($files as $key => $val) {
        if ($key>1) {
            $file=$dir.'/'.$val;
            if (is_dir($file)) {
                deldir($file);
            } else {
                unlink($file);
            }
        }
    }
    rmdir($dir);
}
/**
 * 获取子树
 * @param $array
 * @param int $id
 * @return array
 */
function getTree($array)
{
    static $tree = [];
    foreach ($array as $key => $value) {
        if (isset($array[$value['parent_id']])){
            $array[$value['parent_id']]['child'][]=&$array[$key];
        }else{
            $tree[]=&$array[$key];
        }
    }
    return $tree;
}
/**
 * 管理员操作记录
 * @param $log_url 操作URL
 * @param string $log_info 记录信息
 * @param $log_type 日志类别
 */
function adminLog($log_info,$log_type=0){
    $add['log_time'] = time();
    $add['admin_id'] = session('admin_id');
    $add['log_info'] = $log_info;
    $add['log_ip'] = getIP();
    $add['log_url'] = request()->url();
    Db::name('admin_log')->insert($add);
}
/**
 * 店铺操作记录
 * @param string $log_info 记录信息
 */
function storeLog($log_info){
    $add['store_id'] = session('dianpu_id');
    $add['log_info'] = $log_info;
    $add['log_ip'] = getIP();
    $add['log_url'] = request()->url();
    $add['log_time'] = time();
    Db::name('store_log')->insert($add);
}
// 定义一个函数getIP() 客户端IP，
function getIP(){
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    if(preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/', $ip)){
        return $ip;
    }else{
        return '';
    }
}
//判断是否是在微信中
function is_wx(){
    return strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') ? true : false;
}
/**
 * 获取当前用户的位置
 * @param $ip
 */
function getArea(){
    $ip=request()->ip();
    $map="http://api.map.baidu.com/location/ip?ip=".$ip."&ak=ZmTIZWrqK0bx4eN5fUoNOMr0ElHY6dMG&coor=bd09ll";
//    $map="http://api.map.baidu.com/location/ip?ip=144.0.155.17&ak=ZmTIZWrqK0bx4eN5fUoNOMr0ElHY6dMG&coor=bd09ll";
    $data=file_get_contents($map);
    $data=json_decode($data,true);
    $map=array();
    if ($data['status']==0){
        $map=array(
            'province'      =>      $data['content']['address_detail']['province'],
            'city'          =>      $data['content']['address_detail']['city'],
            'district'      =>      $data['content']['address_detail']['district'],
            'address'       =>      $data['content']['address'],
            'longitude'     =>      $data['content']['point']['x'],
            'latitude'      =>      $data['content']['point']['y'],
        );
    }
    return $map;
}
/**
 * 通过经纬度换区地址
 * @param $latitude 纬度
 * @param $longitude 经度
 */
function getAreaFromLat($latitude,$longitude){
    //判断是安卓还是苹果
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $coordtype = 'gcj02ll';
    //分别进行判断
    if(strpos($agent, 'iphone') || strpos($agent, 'ipad')){
        $coordtype = 'wgs84ll';
    }
    $map="https://api.map.baidu.com/reverse_geocoding/v3/?ak=ZmTIZWrqK0bx4eN5fUoNOMr0ElHY6dMG&output=json&extensions_poi=1&coordtype=wgs84ll&location={$latitude},{$longitude}";
    $data=file_get_contents($map);
    $data=json_decode($data,true);
    $map=array();
    if ($data['status']==0){
        $map=array(
            'formatted_address'      =>      $data['result']['formatted_address'],
            'province'      =>      $data['result']['addressComponent']['province'],
            'city'          =>      $data['result']['addressComponent']['city'],
            'district'      =>      $data['result']['addressComponent']['district'],
            'business'      =>      $data['result']['business'],
            'longitude'     =>      $data['result']['location']['lng'],
            'latitude'      =>      $data['result']['location']['lat'],
        );
    }
    return $map;
}
/**
 * 获取用户手机号
 * @param $user_id 用户id
 */
function getMobile($user_id){
    $mobile=Db::name('users')->where('user_id',$user_id)->value('mobile');
    return $mobile ?? "无";
}
/**
 * 获取用户等级名称
 * @param string $level_id 等级id
 */
function getLevel($level_id){
    if ($level_id==0)return getSysConfig('rate.default_level_name');
    $str=Db::name('user_level')->where('level_id',$level_id)->value('name');
    return $str;
}
/**
 * 获取用户等级名称
 * @param string $level_id 等级id
 */
function getUserLevel($level_id){
    $str=Db::name('user_level')->where('level_id',$level_id)->value('name');
    return $str;
}
//获取真实姓名
function getRealname($user_id){
    $str=Db::name('users')->where('user_id',$user_id)->value('realname');
    return $str;
}
/**
 * 检查手机号码格式
 * @param string $mobile 手机号码
 */
function check_mobile($mobile){
    if(preg_match('/1[3456789]\d{9}$/',$mobile)){
        return true;
    }
    return false;
}
/**
 * 效验手机验证码
 * @param int $mobile 手机号
 * @param int $code 验证码
 */
function yz_sms_code($mobile,$code){
    $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
    if (empty($code)){
        return ['code'=>400,'msg'=>'请输入验证码'];
    }
    $sms=Db::name('sms_log')->where('mobile',$mobile)->find();
    if (empty($sms)){
        return ['code'=>400,'msg'=>'请先获取验证码'];
    }
    if (time()-$sms['add_time']>$sms_time_out){
        return ['code'=>400,'msg'=>'验证码已过期'];
    }
    if ($code!=$sms['code']){
        return ['code'=>400,'msg'=>'验证码不正确'];
    }
    return ['code'=>200,'msg'=>'验证成功'];
}
//生成用户token
function getToken(){
    $b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
    while (true){
        $tmp=array();
        while (count($tmp)<9){//生成9位不同的数字和字母
            //随机打乱并随机取其中一个
            $tmp[]=str_shuffle($b)[mt_rand(0,strlen($b)-1)];
            $tmp=array_unique($tmp);
        }
        $str=implode($tmp,'');
        $user_token=encrypt($str);
        $count = Db::name('users')->where('token',$user_token)->count();
        if ($count==0){
            break;
        }
    }
    return $user_token;
}
//生成唯一推荐码
function getReKey(){
    $str='';
    while (true){
        $tmp=array();
        while (count($tmp)<6){//生成6位不同的数字
            $tmp[]=mt_rand(1,9);
        }
        $str=implode($tmp,'');
        $count = Db::name('users')->where('rekey',$str)->count();
        if ($count==0){
            break;
        }
    }
    return $str;
}
function yc_phone($str){
    $resstr=substr_replace($str,'****',3,4);
    return $resstr;
}
//获取订单号
function getOrderSn($table='order',$prefix=''){
    $order_sn = null;
    // 保证不会有重复订单号存在
    while(true){
        $order_sn =$prefix ? $prefix.date('YmdHis').rand(1000,9999) : date('YmdHis').rand(1000,9999); // 订单编号
        $order_sn_count = Db::name($table)->where("order_sn='$order_sn'")->count();
        if($order_sn_count == 0)
            break;
    }
    return $order_sn;
}
/**
 * 获取用户信息
 * @param string $user_value  用户id 手机 推荐码
 * @param int $type  类型 0 user_id查找 1 手机查找 2 推荐码查找 3身份证查找
 */
function get_user_info($user_value, $type = 0)
{
    $map = [];
    if ($type == 0) {
        $map['user_id'] = $user_value;
    } elseif ($type == 1) {
        $map['mobile'] = $user_value;
    } elseif ($type == 2) {
        $map['rekey'] = $user_value;
    }elseif ($type == 3) {
        $map['idcard'] = $user_value;
    }else{
        return null;
    }
    return Db::name('users')->where($map)->find();
}
/**
 * 增减商品库存销量
 * @param string $order_id 订单id
 * @param int $type 类型 1增加销量减少库存 2减少销量增加库存
 */
function GoodsStoreCount($order_id,$type=1){
    $order=Db::name('order')->where('order_id',$order_id)->find();
    if (!$order){
        return true;
    }
    $log1=$log2=true;
    $order_goods=Db::name('order_goods')->where('order_id',$order_id)->select();
    if ($type==1){
        foreach ($order_goods as $good){
            $goods_update['sales_sum']=Db::Raw("sales_sum+{$good['goods_num']}");
            $goods_update['store_count']=Db::Raw("store_count-{$good['goods_num']}");
            //增加销量 减少库存
            $log1=Db::name('goods')->where('goods_id',$good['goods_id'])->update($goods_update);
            if ($good['item_id']){
                //减少规格库存
                $log2=Db::name('spec_goods_price')->where('item_id',$good['item_id'])->dec('store_count',$good['goods_num'])->update();
            }
        }
    }else{
        foreach ($order_goods as $good){
            $goods_update['sales_sum']=Db::Raw("sales_sum-{$order['goods_num']}");
            $goods_update['store_count']=Db::Raw("store_count+{$order['goods_num']}");
            //减少销量 增加库存
            $log1=Db::name('goods')->where('goods_id',$good['goods_id'])->update($goods_update);
            if ($good['item_id']){
                //增加规格库存
                $log2=Db::name('spec_goods_price')->where('item_id',$good['item_id'])->inc('store_count',$good['goods_num'])->update();
            }
        }
    }
    if ($log1 && $log2){
        return true;
    }else{
        return false;
    }
}
/**
 * 增减认养商品库存销量
 * @param string $order_id 订单id
 * @param int $type 类型 1增加销量减少库存 2减少销量增加库存
 */
function FosterGoodsStoreCount($order_id,$type=1){
    $order=Db::name('foster_order')->where('order_id',$order_id)->find();
    if (!$order){
        return true;
    }
    if ($type==1){
        $goods_update['sales_sum']=Db::Raw("sales_sum+{$order['goods_num']}");
        $goods_update['store_count']=Db::Raw("store_count-{$order['goods_num']}");
        //增加销量 减少库存
        $log=Db::name('foster_goods')->where('goods_id',$order['goods_id'])->update($goods_update);
    }else{
        $goods_update['sales_sum']=Db::Raw("sales_sum-{$order['goods_num']}");
        $goods_update['store_count']=Db::Raw("store_count+{$order['goods_num']}");
        //减少销量 增加库存
        $log=Db::name('goods')->where('goods_id',$order['goods_id'])->update($goods_update);
    }
    if ($log){
        return true;
    }else{
        return false;
    }
}
/**
 * 获取配置
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return bool
 */
function getSysConfig($config_key,$data = array()){
    $param = explode('.', $config_key);
    $cache_key = $param[0] . '_' . config('site.uniacid');

    if(empty($data)){
        //如$config_key=shop_info则获取网站信息数组
        $config = cache($cache_key);//直接获取缓存
        if (empty($config)){
            $res = Db::name('config')->where("inc_type",$param[0])->select();
            foreach($res as $k=>$val){
                $config[$val['name']] = $val['value'];
            }
            cache($cache_key,$config);
        }
        if(count($param)>1){
            return $config[$param[1]];
        }else{
            return $config;
        }
    }else{
        //插入或更新数据
        $result =  Db::name('config')->where("inc_type", $param[0])->select();
        if($result){
            foreach($result as $val){
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k => $v){
                $newArr = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
                if(!isset($temp[$k])){
                    Db::name('config')->insert($newArr);//新key数据插入数据库
                }else{
                    if($v!=$temp[$k]){
                        Db::name('config')->where("name", $k)->update($newArr);//key存在且值有变更新此项
                    }
                }
            }
            //更新后的数据库记录
            $newRes = Db::name('config')->where("inc_type", $param[0])->select();
            foreach ($newRes as $rs){
                $newData[$rs['name']] = $rs['value'];
            }
        }else{
            foreach($data as $k=>$v){
                $newArr[] = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
            }
            Db::name('config')->insertAll($newArr);
            $newData = $data;
        }
        return cache($cache_key,$newData);
    }
}
/**
 * 记录账户变动
 * @param string $user_id 用户id
 * @param int $money 金额
 * @param string $desc 描述
 * @param int $type 变动类型1粮票2积分3牧场补贴4储备金
 * @param int $gid 触发奖励用户id
 * @param int $order_id 订单id
 * @param string $order_sn 订单编号
 * @param float $lj_sy 累积收益
 * @param int $wid wallet表id
 * @return bool
 */
function accountLog($user_id, $money=0, $desc = '',$type=1 ,$gid=0 , $order_id = 0 ,$order_sn = '',$lj_sy=0,$wid=0){
    $user=get_user_info($user_id);
    if (empty($user)){
        write_log($user_id,"资金变动失败,会员{$user_id}不存在,order_id={$order_id}");
        return true;
    }
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id'     => $user_id,
        'gid'         => $gid,
        'wid'         => $wid,
        'money'       => $money,
        'type'        => $type,
        'add_time'    => time(),
        'desc'        => $desc,
        'order_id'    => $order_id,
        'order_sn'    => $order_sn
    );
    if($money == 0)return false;
    switch ($type){
        case 1:
            $user_update['user_money']=Db::raw("user_money+$money");
            break;
        case 2:
            $user_update['jifen']=Db::raw("jifen+$money");
            break;
        case 3:
            $user_update['mcbt']=Db::raw("mcbt+$money");
            break;
        case 4:
            $user_update['reserve_money']=Db::raw("reserve_money+$money");
            break;
        default:
            if($wid==0){
                return false;
            }
    }
    if ($lj_sy>0){
        $user_update['lj_sy']=Db::raw("lj_sy+$lj_sy");
    }
    if ($user_update){
        $update = Db::name('users')->where("user_id",$user_id)->update($user_update);
    }else{
        $update = true;
    }
    if($update){
        Db::name('account_log')->insert($account_log);
        return true;
    }else{
        return false;
    }
}
/**
 * 记录某票变动
 * @param string $user_id 用户id
 * @param string $u_wid user_wallet表id
 * @param float $money 金额
 * @param string $desc 描述
 * @param int $gid 触发奖励用户id
 * @param int $wid wallet表id
 * @return bool
 */
function user_wallet_log($user_id,$u_wid,$money,$desc = '',$gid=0,$wid=0){
    $user=get_user_info($user_id);
    if (empty($user)){
        write_log('systeam',"某票变动失败,会员{$user_id}不存在");
        return true;
    }
    if($money == 0)return false;
    //如果没有当前类型的钱包 则创建一个
    if ($u_wid==0){
        $find=UserWallet::where("user_id={$user_id} and wid=$wid")->find();
        if ($find){
            $user_wallet_update['money']=Db::raw("money+$money");
            $u_wid=$find->id;
            $update = $find->save($user_wallet_update);
        }else{
            $user_wallet_insert['user_id']=$user_id;
            $user_wallet_insert['wid']=$wid;
            $user_wallet_insert['money']=$money;
            $model=UserWallet::create($user_wallet_insert);
            $u_wid=$model->id;
            $update=true;
        }
    }else{
        $user_wallet_update['money']=Db::raw("money+$money");
        $update = Db::name('user_wallet')->where("id",$u_wid)->update($user_wallet_update);
    }
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id'     => $user_id,
        'gid'         => $gid,
        'u_wid'       => $u_wid,
        'money'       => $money,
        'desc'        => $desc,
        'add_time'    => time(),
    );
    if($update){
        Db::name('user_wallet_log')->insert($account_log);
        return true;
    }else{
        return false;
    }
}
/**
 * 写入日志
 * @param string $user_id 用户id
 * @param string $info 写入内容
 */
function write_log($user_id,$info){
    /*$debugInfo = debug_backtrace()[0];
    if (is_array($info)) {
        $info = json_encode($info);
    }
    // 写入调用时间、文件名，所在行号，内容
    // $content = sprintf("%s user_id=%s %s %d行 %s \n", date('Y-m-d H:i:s'),$user_id,CONTROLLER_NAME.".php", $debugInfo['line'], $info);
    $content = sprintf("%s user_id=%s %s %d行 %s \n", date('Y-m-d H:i:s'),$user_id,"log.php", $debugInfo['line'], $info);
    $file  = root_path()."log/$user_id.txt";//要写入文件的文件名（可以是任意文件名），如果文件不存在，将会创建一个
    $f=file_put_contents($file,$content,FILE_APPEND);
    return $f;*/
}
function exportExcel($expTitle,$expCellName,$expTableData){
    $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum = count($expCellName);
    $dataNum = count($expTableData);
    require_once root_path('vendor/PHPExcel').'PHPExcel.php';
    $objPHPExcel = new PHPExcel();
    $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
//    $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
    // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
    for($i=0;$i<$cellNum;$i++){
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'1', $expCellName[$i][1]);
    }
    // Miscellaneous glyphs, UTF-8
    for($i=0;$i<$dataNum;$i++){
        for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), $expTableData[$i][$expCellName[$j][0]]);
        }
    }
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}
/**
 * 导出excel
 * @param string $strTable 表格内容
 * @param string $filename 文件名
 */
function downloadExcel($strTable,$filename)
{
    header("Content-type: application/vnd.ms-excel");
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=".$filename."_".date('Y_m_d').".xls");
    header('Expires:0');
    header('Pragma:public');
    echo '<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.$strTable.'</html>';
}
/**
 * 获取3层及以下团队id
 * @param $user_id 用户id
 */
function get_three_td_ids($user_id){
    $ids=$user_id;
    $list=array();
    $i=0;
    while (true){
        $i++;
        $list1=Db::name('users')->whereIn('reid',"$ids")->column('user_id');
        if ($i<3){
            if (empty($list1)){
                return [];
            }
            $ids=implode(',',$list1);
            continue;
        }
        $list=array_merge($list1,$list);
        if (empty($list1)){
            break;
        }
        $ids=implode(',',$list1);
    }
    if ($list){
        sort($list);
    }
    return $list;
}
//功能：计算两个时间戳之间相差的日时分秒
//$begin_time 开始时间戳
//$end_time 结束时间戳
function timediff($begin_time,$end_time)
{
    if($begin_time < $end_time){
        $starttime = $begin_time;
        $endtime = $end_time;
    }else{
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    //计算天数
    $timediff = $endtime-$starttime;
    $days = intval($timediff/86400);
    //计算小时数
    $remain = $timediff%86400;
    $hours = intval($remain/3600);
    //计算分钟数
    $remain = $remain%3600;
    $mins = intval($remain/60);
    //计算秒数
    $secs = $remain%60;
    $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
    return $res;
}
/**
 * 获取所有的团队用户id 按照节点关系
 * @param string $user_id 用户id
 * @param int $limit 限制多少层
 * @param $count 0获取团队id 1获取团队人数
 * @param $ceng int 获取某一层的会员id
 */
function get_node_ids($user_id,$limit=0,$count=0,$ceng=0){
    $ids=$user_id;
    $list=array();
    $i=0;
    while (true){
        $i++;
        $list1=Db::name('users')->whereIn('node_id',"$ids")->column('user_id');
        if($ceng>0 && $ceng==$i){
            return $list1;
        }
        $list=array_merge($list1,$list);
        if ($limit>0){
            if ($i>=$limit){
                break;
            }
        }
        if (empty($list1)){
            if($ceng>0){
                return [];
            }
            break;
        }
        $ids=implode(',',$list1);
    }
    if ($count==0){
        sort($list);
        return $list;
    }else{
        return count($list);
    }
}
/**
 * 获取伞下可看到订单的团队用户id
 * @param string $user_id 用户id
 */
function get_order_td_ids($user_id){
    $level=Db::name('users')->where('user_id',$user_id)->value('level');
    $list=[];
    if ($level<5){
        $zt_users=Users::where("reid={$user_id}")->select();
        foreach ($zt_users as $zt_user){
            if ($zt_user['level']<$level){
                $list[]=$zt_user['user_id'];
            }else{
                break;
            }
        }
    }else{
        $ids=[$user_id];
        while (true){
            $where[]=['reid','in',$ids];
            $where[]=['level','<',$level];
            $list1=Db::name('users')->where($where)->column('user_id');
            unset($where);
            $list=array_merge($list1,$list);
            if (empty($list1)){
                break;
            }
            $ids=implode(',',$list1);
        }
    }
    return $list;
}
/**
 * 获取所有的团队用户id
 * @param string $user_id 用户id
 * @param int $limit 限制多少层
 * @param int $count 0获取团队id 1获取团队人数
 * @param int $ceng 获取某一层的会员id
 */
function get_td_ids($user_id,$limit=0,$count=0,$ceng=0){
    $ids=$user_id;
    $list=[];
    $i=0;
    while (true){
        $i++;
        $list1=Db::name('users')->whereIn('reid',"$ids")->column('user_id');
        if($ceng>0 && $ceng==$i){
            return $list1;
        }
        $list=array_merge($list1,$list);
        if ($limit>0){
            if ($i>=$limit){
                break;
            }
        }
        if (empty($list1)){
            if($ceng>0){
                return [];
            }
            break;
        }
        $ids=implode(',',$list1);
    }
    if ($count==0){
        sort($list);
        return $list;
    }else{
        return count($list);
    }
}
/**
 * 获取用户在团队的第几层
 * @param string $user_id 用户id
 * @param int $count 上级id
 * @param string $field reid推荐关系node_id节点关系
 */
function get_td_cengji($user_id,$reid,$field='reid'){
    $i=0;
    $uid=$user_id;
    while (true){
        $user=Db::name('users')->where('user_id',$uid)->find();
        $i++;
        if ($user[$field]==$reid || empty($user)){
            break;
        }
        $uid=$user[$field];
    }
    return $i;
}
function update_pay_status($order_sn,$transaction_id='')
{
    if(stripos($order_sn,'r') !== false){
        //用户充值
        $order_where['order_sn']=$order_sn;
        $order_where['order_status']=-1;
        $order = Recharge::where($order_where)->find();
        if (empty($order)){
            //看看有没已经处理过这笔订单  支付宝返回不重复处理操作
            return false;
        }
        $order_update['order_status']=1;
        $order_update['pay_time']=time();
        if ($transaction_id){
            $order_update['transaction_id']=$transaction_id;
        }
        $order->save($order_update);
        $money=$order['order_amount'];
        accountLog($order['user_id'],$money,"用户充值",2);
    }else if(stripos($order_sn,'f') !== false){
        $order_where['order_sn']=$order_sn;
        $order_where['order_status']=-1;
        $order = FosterOrder::where($order_where)->find();
        if (empty($order)){
            return false;
        }
        $order_update['order_status']=1;
        $order_update['pay_time']=time();
        if ($transaction_id){
            $order_update['transaction_id']=$transaction_id;
        }
        $order->save($order_update);
        if ($order['reduce']==2){//减少库存增加销量
            FosterGoodsStoreCount($order['order_id']);
        }
        //发放奖励
        foster_jl_base($order['order_id']);
    }else{
        //订单
        $order_where['order_sn']=$order_sn;
        $order_where['order_status']=-1;
        $order = Order::where($order_where)->find();
        if (empty($order)){
            //看看有没已经处理过这笔订单  支付宝返回不重复处理操作
            return false;
        }
        $order_update['order_status']=1;
        $order_update['pay_time']=time();
        if ($transaction_id){
            $order_update['transaction_id']=$transaction_id;
        }
        $order->save($order_update);
        if ($order['reduce']==2){//减少库存增加销量
            GoodsStoreCount($order['order_id']);
        }
        //将订单商品更新为已支付 统计使用
        Db::name('order_goods')->where('order_id',$order['order_id'])->update(['is_zhifu'=>1,'pay_time'=>time()]);
        jl_base($order['order_id']);
    }
}
/**
 * 发放奖励(包括赠送储备金、额外收益等)
 * @param string $order_id
 */
function foster_jl_base($order_id){
    $order=FosterOrder::find($order_id);
    if (empty($order)){
        write_log('system',"发放奖励失败,订单{$order_id}不存在");
        return false;
    }
    //赠送储备金
    if ($order['given_cbj']>0){
        accountLog($order['user_id'],$order['given_cbj'],'购物赠送',4,0,$order_id,$order['order_sn']);
    }
    //额外收益
    if ($order['extra_wid'] && $order['extra_text']){
        foreach ($order['extra_text'] as $extra){
            $foster_order_extra_model=new FosterOrderExtra();
            $insert['oid']=$order_id;
            $insert['user_id']=$order['user_id'];
            $insert['extra_wid']=$order['extra_wid'];
            $insert['lq_time']=$extra['lq_time'];
            $insert['lq_number']=$extra['number'];
            $foster_order_extra_model->save($insert);
        }
    }
    //处理加速释放
    if ($order['re_speed'] && $order['user']['reid']){
        $uid=$order['user']['reid'];
        $goods_num=$order['goods_num'];
        $arr=explode(',',$order['re_speed']);
        for ($i=0;$i<count($arr);$i++){
            $reuser=Users::find($uid);
            if ($reuser){
                //查询最早的订单
//                $order_where="user_id={$uid} and order_status>0 and surplus_yield>0";
                $order_where="user_id={$uid} and order_status=1";
                $re_order=FosterOrder::where($order_where)->find();
                if ($re_order){
                    //数量*每日收益*加速比例
                    $jiasu=$goods_num*$order['day_sy']*($arr[$i]/100);
                    if ($jiasu>0){
                        $re_order_update['speed']=Db::Raw("speed+{$jiasu}");
                        $re_order->save($re_order_update);
                    }
                }
                $uid=$reuser['reid'];
            }else{
                break;
            }
        }
    }
    //增加累计认养业绩 日认养业绩 团队认养业绩
    $user_update['lj_ry_yeji']=Db::Raw("lj_ry_yeji+{$order['order_amount']}");
    $user_update['month_ry_yeji']=Db::Raw("month_ry_yeji+{$order['order_amount']}");
    $user_update['day_ry_yeji']=Db::Raw("day_ry_yeji+{$order['order_amount']}");
    Db::name('users')->where('user_id',$order['user_id'])->update($user_update);
    //累计认养业绩变动 升级会员级别
    update_user_level($order['user_id']);
    //增加团队认养业绩
    add_td_ry_yeji($order['user_id'],$order);
    //团队分红
    td_fh($order);
    //直推奖励
    zt_jl($order);
    //给商家结算 按照成本价
    $store_user=$order['store']['user'];
    $cost_price=$order['cost_price']*$order['goods_num'];
    if ($store_user && $cost_price){
        accountLog($store_user['user_id'],$cost_price,"订单结算",1,$order['user_id']);
    }
}
/**
 * 直推奖励-----新增
 * 发给上级  按照储备金释放比例
 * @param $order array 订单信息
 */
function zt_jl($order){
    $user=Users::find($order['user_id']);
    if (empty($user)){
        write_log('system',"发放直推奖励失败,会员{$order['user_id']}不存在");
        return false;
    }
    if (empty($user['reid'])){
        return true;
    }
    //储备金积分释放比例
    $cbj_sf_jifen_bl=getSysConfig('rate.cbj_sf_jifen_bl');
    $order_amount=$order['order_amount'];
    $reuser=Users::find($user['reid']);
    if ($reuser && $reuser['dengji']['cbj_sf_bl']>0){
        $amount=$order_amount*($reuser['dengji']['cbj_sf_bl']/100);
        $amount=round($amount,3);
        if ($amount>0){
            $true_amount=min($amount,$reuser['reserve_money']);
            //减少储备金 增加积分和牧场补贴
            $jifen=$true_amount*($cbj_sf_jifen_bl/100);
            $mcbt=$true_amount-$jifen;
            if ($jifen>0){
                accountLog($reuser['user_id'],$jifen,"储备金释放",2);
            }
            if ($mcbt>0){
                accountLog($reuser['user_id'],$mcbt,"储备金释放",3);
            }
            //减少储备金
            if ($true_amount>0){
                accountLog($reuser['user_id'],-$true_amount,"储备金释放",4);
            }
        }
    }
    return true;
}
/**
 * 团队分红
 * @param \think\Model $order
 */
function td_fh($order){
    $user=Users::find($order['user_id']);
    if (empty($user)){
        write_log('system',"发放团队分红失败,会员{$order['user_id']}不存在");
        return false;
    }
    if (empty($user['reid'])){
        return true;
    }
    $order_amount=$order['order_amount'];
    $jl_bili=0;
    $uid=$user['reid'];
    while (true){
        $reuser=Users::find($uid);
        if ($reuser){
            if ($reuser['dengji']['jl_bili']>$jl_bili){
                //判断当前会员是否能拿到奖励
                $can_jl=can_level_jl($uid,$reuser['level']);
                if ($can_jl){
                    $jl_bl=$reuser['dengji']['jl_bili']-$jl_bili;
                    if ($jl_bl>0){
                        $jl_money=$order_amount*($jl_bl/100);
                        $jl_money=round($jl_money,2);
                        if ($jl_money>0){
                            $desc=sprintf('%s团队分红',$reuser['dengji']['name']);
                            inset_jl_log($uid,$reuser['level'],$order_amount,$jl_bl,$jl_money,$desc);
                        }
                    }
                    $jl_bili=$reuser['dengji']['jl_bili'];
                }
            }
            $uid=$reuser['reid'];
        }else{
            break;
        }
    }
    return true;
}
/**
 * 发放奖励(二级分销奖励等)
 * @param string $order_id
 */
function jl_base($order_id){
    $order=Order::find($order_id);
    if (empty($order)){
        write_log('system',"发放奖励失败,订单{$order_id}不存在");
        return false;
    }
    $user=$order['user'];
    if (empty($user)){
        write_log('system',"发放奖励失败,会员{$order['user_id']}不存在");
        return false;
    }
    //增加个人累计消费
    $user_update['lj_xf']=Db::Raw("lj_xf+{$order['order_amount']}");
    Db::name('users')->where('user_id',$user['user_id'])->update($user_update);
    return true;
}
/**
 * 给商家结算
 * @param int $order_id 订单id
 * @param int $type 类型1商城订单2认养订单
 */
function store_settle($order_id){
    $order=Order::find($order_id);
    if (empty($order)){
        write_log('system',"给商家结算,订单{$order_id}不存在");
        return false;
    }
    $user=$order['user'];
    if (empty($user)){
        write_log('system',"给商家结算,会员{$order['user_id']}不存在");
        return false;
    }
    //todo 二级分销奖励，奖励的是积分 奖励金额是不是要加上运费
    $uid=$user['reid'];
    if ($order['award'] && $uid){
        $arr=explode(',',$order['award']);
        for ($i=0;$i<count($arr);$i++){
            $reuser=Users::find($uid);
            if ($reuser){
                $jl_jifen=$order['total_amount']*($arr[$i]/100);
                if ($jl_jifen>0){
                    accountLog($uid,$jl_jifen,'分销奖励',2,$user['user_id'],$order_id,$order['order_sn']);
                }
                $uid=$reuser['reid'];
            }else{
                break;
            }
        }
    }
    //按照成本价结算
    $store_user=$order['store']['user'];
    if ($store_user && $order['cost_price']){
        accountLog($store_user['user_id'],$order['cost_price'],"订单结算",1,$user['user_id'],$order_id,$order['order_sn']);
    }
}
function inset_recharge_log($user_id,$type,$wid,$money,$desc=''){
    $insert['user_id']=$user_id;
    $insert['type']=$type;
    $insert['wid']=$wid;
    $insert['money']=$money;
    $insert['desc']=$desc;
    UserRechargeLog::create($insert);
}
function inset_jl_log($user_id,$level,$amount,$jl_bili,$money,$desc){
    $insert['user_id']=$user_id;
    $insert['level']=$level;
    $insert['amount']=$amount;
    $insert['jl_bili']=$jl_bili;
    $insert['money']=$money;
    $insert['desc']=$desc;
    JlLog::create($insert);
}
//处理订单自动取消 每隔一分钟执行
function order_qx_auto(){
    $order_model=new Order();
    //待付款订单多少时间内未付款，系统自动取消订单 单位为分钟
    $auto_qx_time=getSysConfig('shopping.auto_qx_time');
    $time=time();
    $auto_qx_end=$auto_qx_time*60;
    $auto_qx_where="order_status=-1 and (add_time+$auto_qx_end<=$time)";
    $auto_qx_order=$order_model->whereRaw($auto_qx_where)->field('order_id,reduce,order_sn')->select();
    foreach ($auto_qx_order as $auto_qx){
        if ($auto_qx['reduce']==1){
            GoodsStoreCount($auto_qx['order_id'],2);//减少销量增加库存
        }
        $auto_qx->cancel_time=time();
        $auto_qx->order_status=-2;
        $auto_qx->save();
    }
}
//处理订单自动确认 每隔一分钟执行
function order_qr_auto(){
    $order_model=new Order();
    //发货后多少时间系统自动确认收货 单位为天
    $auto_qr_time=getSysConfig('shopping.auto_qr_time');
    $time=time();
    $auto_qr_end=$auto_qr_time*86400;
    $auto_qr_where="order_status=2 and (shipping_time+$auto_qr_end<=$time)";
    $auto_qr_order=$order_model->whereRaw($auto_qr_where)->field('order_id')->select();
    foreach ($auto_qr_order as $auto_qr){
        $auto_qr->order_status=3;
        $auto_qr->confirm_time=time();
        $auto_qr->save();
        //给商家结算
        store_settle($auto_qr->order_id);
    }
}
//认养额外收益自动发放 每分钟执行
function foster_order_extra_auto(){
    $time=time();
    $where="$time>=lq_time and status=-1";
    $list=FosterOrderExtra::where($where)->select();
    foreach ($list as $value){
        if ($value['lq_number']>0){
            //todo 要乘以购买数量？
            $lq_number=$value['lq_number']*$value['dingdan']['goods_num'];
            user_wallet_log($value['user_id'],0,$lq_number,"每日收益",0,$value['extra_wid']);
        }
        $value->status=1;
        $value->end_time=time();
        $value->save();
    }
}
//交易自动回收 每分钟执行
function deal_recycle_auto(){
    $time=time();
    //超出多长时间的交易系统回收 单位为小时
    $deal_recycle_time=getSysConfig('rate.deal_recycle_time');
    $end_time=$deal_recycle_time*3600;
    $where="status=-1 and (add_time+$end_time<=$time)";
    $model=new UserWalletDeal();
    $list=$model->where($where)->select();
    foreach ($list as $val){
        $order_amount=$val['amount']-$val['jy_sxf'];
        $desc=sprintf('出售%s收入',$val['qianbao']['name']);
        accountLog($val['user_id'],$order_amount,$desc);
        $val->end_time=time();
        $val->status=2;
        $val->save();
    }
}
//获取等级分红总销售业绩
function get_level_amount($level_id){
    $amount=0;
    for ($i=0;$i<$level_id;$i++){
        $num=$i+1;
        $amount+=Db::name('users')->where("1=1")->sum("day_level{$num}_xf");
    }
    return $amount;
}
//用户数据归0 每天0点执行
function user_auto(){
    //用户是否已领取 饲料归0
    $update['is_fodder']=0;
    $update['fodder']=0;
    Db::name('users')->where("1=1")->update($update);
}
//认养订单归0 每天0点执行
function order_auto(){
    $order_update['feed_status']=1;
    Db::name('foster_order')->whereRaw("order_status=1")->update($order_update);
}
//团队月业绩清零
function td_month_yeji_auto(){
    $update['td_month_yeji']=0;
    Db::name('users')->whereRaw("td_month_yeji>0")->update($update);
}
//储备金释放 每天0点执行
function cbj_sf_auto(){
    //储备金积分释放比例
    $cbj_sf_jifen_bl=getSysConfig('rate.cbj_sf_jifen_bl');
    $level_ids=UserLevel::whereRaw("cbj_sf_bl>0")->column('level_id');
    if ($level_ids){
        $level_ids=implode(',',$level_ids);
        $user_where="is_lock=0 and reserve_money>0 and level in ($level_ids)";
        $users=Users::whereRaw($user_where)->field("user_id,reid,level,reserve_money")->select();
        foreach ($users as $user){
            /********************{此处修改为按照不清零的团队业绩和自己累积消费来算}********************/
            $xq_ids=get_xq_td_ids($user['user_id'],'td_ry_yeji+lj_ry_yeji');
            $amount=0;
            foreach ($xq_ids as $xq){
                //计算本条线释放金额 （团队业绩+自己消费）*(3%-1%)
                $temp_user=Users::where("user_id={$xq}")->field("(day_td_ry_yeji) as yeji,day_ry_yeji,level")->find();
                if ($temp_user && $temp_user['yeji']>0){
                    $bili=($user['dengji']['cbj_sf_bl']/100)-($temp_user['dengji']['cbj_sf_bl']/100);
                    $temp_amount=$temp_user['yeji']*$bili;
                    /********************{此处不要了}********************/
//                    $temp_amount1=$temp_user['day_ry_yeji']*($user['dengji']['cbj_sf_bl']/100);
                    if ($temp_amount>0){
                        $amount+=$temp_amount;
                    }
//                    if ($temp_amount1>0){
//                        $amount+=$temp_amount1;
//                    }
                }
            }
            if ($amount>0){
                $true_amount=min($amount,$user['reserve_money']);
                //减少储备金 增加积分和牧场补贴
                $jifen=$true_amount*($cbj_sf_jifen_bl/100);
                $mcbt=$true_amount-$jifen;
                if ($jifen>0){
                    accountLog($user['user_id'],$jifen,"储备金释放(级差)",2);
                }
                if ($mcbt>0){
                    accountLog($user['user_id'],$mcbt,"储备金释放(级差)",3);
                    //发放平级奖励
                    pj_jl($user,$user['dengji'],$mcbt);
                }
                //减少储备金
                if ($true_amount>0){
                    accountLog($user['user_id'],-$true_amount,"储备金释放",4);
                }
            }
        }
    }
    $update['day_ry_yeji']=0;
    $update['day_td_ry_yeji']=0;
    $update['is_fodder']=0;
    $update['fodder']=0;
    Db::name('users')->where("1=1")->update($update);
}
/**
 * 发放平级奖励
 * @param array $user 用户信息
 * @param array $level 等级信息
 * @param float $mcbt 牧场补贴金额
 */
function pj_jl($user,$level,$mcbt){
    if ($level['pj_jl']<=0 || empty($user['reid'])){
        return true;
    }
    //储备金积分释放比例
    $cbj_sf_jifen_bl=getSysConfig('rate.cbj_sf_jifen_bl');
    /********************{改为一直往上找 找到级别大的就退出 找到级别一样的就发}********************/
    $uid=$user['reid'];
    while (true){
        $reuser=Users::find($uid);
        if ($reuser){
            if ($reuser['level']>=$user['level']){
                if ($reuser['level']==$user['level']){
                    /********************{修改为和储备金释放一样}********************/
                    //计算平级奖励
                    $pj_jl_money=$mcbt*($level['pj_jl']/100);
                    $true_amount=min($pj_jl_money,$reuser['reserve_money']);
                    if ($true_amount>0){
                        //减少储备金 增加积分和牧场补贴
                        $jifen=$true_amount*($cbj_sf_jifen_bl/100);
                        $mcbt=$true_amount-$jifen;
                        if ($jifen>0){
                            accountLog($reuser['user_id'],$jifen,"储备金释放(平级)",2,$user['user_id']);
                        }
                        if ($mcbt>0){
                            accountLog($reuser['user_id'],$mcbt,"储备金释放(平级)",3,$user['user_id']);
                        }
                        //减少储备金
                        accountLog($reuser['user_id'],-$true_amount,"储备金释放",4,$user['user_id']);
                    }
                }
                break;
            }
            $uid=$reuser['reid'];
        }else{
            break;
        }
    }
    return true;
}
//团队自动分红 每天0点执行
function td_fh_auto(){
    //每月分红时间
    $td_fh_time=getSysConfig('rate.td_fh_time');
    //今天是几号
    $d=date('d');
    if ($d!=$td_fh_time){
        return true;
    }
    $where="status=-1";
    $update['status']=1;
    Db::name('jl_log')->whereRaw($where)->update($update);
}
//加权自动分红 每天0点执行
function jq_fh_auto(){
    //每月分红时间
    $jq_fh_time=getSysConfig('rate.jq_fh_time');
    //今天是几号
    $d=date('d');
    if ($d!=$jq_fh_time){
        return true;
    }
    //统计月认养业绩
    $month_ry_where="is_lock=0";
    $month_ry_yeji=Db::name('users')->whereRaw($month_ry_where)->sum('month_ry_yeji');
    if ($month_ry_yeji<=0){
        return true;
    }
    $level_list=Db::name('user_level')->whereRaw('jq_jl_bili>0')->field('level_id,name,jq_jl_bili')->select();
    foreach ($level_list as $level){
        $where="is_lock=0 and level={$level['level_id']}";
        $list=Db::name('users')
            ->whereRaw($where)
            ->field("user_id")
            ->select();
        if (!$list->isEmpty()){
            $count=$list->count();
            $jl_money=$month_ry_yeji*($level['jq_jl_bili']/100);
            $jl_money=round($jl_money/$count,2);
            if ($jl_money>0){
                $desc="{$level['name']}加权分红";
                foreach ($list as $user){
                    $insert['type']=2;
                    $insert['user_id']=$user['user_id'];
                    $insert['money']=$jl_money;
                    $insert['desc']=$desc;
                    JlLqLog::create($insert);
                    accountLog($user['user_id'],$jl_money,$desc,1,0,0,'',$jl_money);
                }
            }
        }
    }
    //用户月认养业绩归0
    $update['month_ry_yeji']=0;
    Db::name('users')->where("1=1")->update($update);
}
/**
 * 根据业绩获取应该奖励的比例 0|1,100|2,200|3,500|4,2000|5
 * @param $yeji float 业绩
 */
function get_yj_bl($yeji){
    $month_fh=getSysConfig('rate.month_fh');
    $arr=explode(',',$month_fh);
    $crr=[];
    foreach ($arr as $key => $val){
        $brr=explode('|',$val);
        $crr[$brr[0]]=$brr[1];
    }
    $bili=0;
    foreach ($crr as $k => $value){
        if ($yeji>=$k){
            $bili=$value;
        }else{
            break;
        }
    }
    return $bili;
}
//签到自动任务 每天0点执行
function sign_auto(){
    $list=Db::name('user_sign')
        ->whereDay('add_time','yesterday')
        ->column("user_id");
    //如果今天是1号 全部累积签到天数归0
    if (date('d')=='1'){
        $where="1=1";
    }else{
        $where[]=['user_id','not in',$list];
    }
    //把没签到的累积签到天数归0
    $update['lj_sign']=0;
    Db::name('users')->where($where)->update($update);
}
/**
 * 无限级增加团队人数以及增加推荐人直推人数(注册了就加)
 * @param $user_id string 用户id
 * @return bool
 */
function td_all_num($user_id){
    $user=get_user_info($user_id);
    if (!$user || !$user['reid']){//推荐人不存在直接返回
        return true;
    }
    $uid=$user['reid'];
    //增加推荐人直推总人数
    $log=Db::name('users')->where('user_id',$uid)->inc('zt_all_num')->update();
    $log1=true;
    while (true){
        $reuser=Db::name('users')->where('user_id',$uid)->find();
        if ($reuser){
            //增加团队总人数
            $log1=Db::name('users')->where('user_id',$uid)->inc('td_all_num')->update();
            $uid=$reuser['reid'];
        }else{
            break;
        }
    }
    if ($log && $log1){
        return true;
    }else{
        return false;
    }
}
/**
 * 增加推荐人直推人数、无限级增加团队人数
 * @param string $user_id 用户id
 * @return bool
 */
function td_num($user_id){
    $user=get_user_info($user_id);
    if (!$user || !$user['reid']){//推荐人不存在直接返回
        return true;
    }
    $uid=$user['reid'];
    //增加推荐人直推有效人数
    $log=Db::name('users')->where('user_id',$uid)->inc('zt_num')->update();
    $log1=true;
    while (true){
        $reuser=get_user_info($uid);
        if ($reuser){
            //增加团队有效人数
            $td_update['td_num']=Db::raw('td_num+1');
            $log1=Db::name('users')->where('user_id',$uid)->update($td_update);
            $uid=$reuser['reid'];
        }else{
            break;
        }
    }
    if ($log && $log1){
        return true;
    }else{
        write_log($user_id,"触发会员user_id={$user_id},增加推荐人直推人数、无限级增加团队人数失败,log={$log}&log1={$log1}");
        return false;
    }
}
/**
 * 无限级增加团队业绩 按照节点关系
 * @param $user_id int 购物用户id
 * @param $order array 订单信息
 */
function td_yeji($user_id,$order){
    $user=get_user_info($user_id);
    if (!$user || !$user['reid']){//推荐人不存在直接返回
        return true;
    }
    $uid=$user['reid'];
    $log=true;
    while (true){
        $reuser=Users::find($uid);
        if ($reuser){
            //增加团队业绩
            $user_update['td_yeji']=Db::raw("td_yeji+{$order['order_amount']}");
            $log=Db::name('users')->where('user_id',$uid)->update($user_update);
            unset($user_update);
            $uid=$reuser['reid'];
        }else{
            break;
        }
    }
    if ($log){
        return true;
    }else{
        return false;
    }
}
/**
 * 无限级增加团队业绩 按照推荐关系
 * @param $user_id int 购物用户id
 * @param $order array 订单信息
 */
function add_td_ry_yeji($user_id,$order){
    $user=get_user_info($user_id);
    if (!$user || !$user['reid']){//推荐人不存在直接返回
        return true;
    }
    $uid=$user['reid'];
    $log=true;
    $order_amount=$order['order_amount'];
    while (true){
        $reuser=Users::find($uid);
        if ($reuser){
            //增加团队认养业绩
            $user_update['day_td_ry_yeji']=Db::raw("day_td_ry_yeji+{$order_amount}");
            $user_update['td_month_yeji']=Db::raw("td_month_yeji+{$order_amount}");
            $user_update['td_ry_yeji']=Db::raw("td_ry_yeji+{$order_amount}");
            $log=Db::name('users')->where('user_id',$uid)->update($user_update);
            unset($user_update);
            //团队认养业绩变动 升级会员级别
            update_user_level($uid);
            $uid=$reuser['reid'];
        }else{
            break;
        }
    }
    if ($log){
        return true;
    }else{
        return false;
    }
}
/**
 * 升级会员级别
 * @param string $user_id 会员id
 */
function update_user_level($user_id){
    $user=Users::find($user_id);
    if (empty($user)){
        write_log('system',"升级会员级别失败,会员{$user_id}不存在");
        return false;
    }
    //判断用户升级
    $level_id=get_update_level_id($user['user_id']);
    if ($level_id>$user['level']){
        $user_update['level']=$level_id;
//        if ($user['valid_time']==0){
//            $user_update['valid_time']=time();
//            td_num($user['user_id']);
//        }
        Db::name('users')->where('user_id',$user_id)->update($user_update);
        if ($user['reid']){
            return update_user_level($user['reid']);
        }
        return $level_id;
    }
    write_log('system',"给{$user_id}--升级,升级到的级别--{$level_id}");
    return $user['level'];
}
/**
 * 升级会员级别
 * @param int $user_id 会员id
 */
function get_update_level_id($user_id){
    $level_list=Db::name('user_level')->select();
    $user=Users::find($user_id);
    $level_id=0;
    foreach ($level_list as $level){
        $tiaojian1=$tiaojian2=$tiaojian3=$tiaojian4=true;
        if ($level['lj_ry_yeji']>0 && $level['lj_ry_open']==1){
            $tiaojian1=$user['lj_ry_yeji']>=$level['lj_ry_yeji'];
        }
        if ($level['td_ry_yeji']>0 && $level['td_ry_yeji_open']==1){
            $tiaojian2=$user['td_ry_yeji']>=$level['td_ry_yeji'];
        }
        if ($level['dsc_ry_yeji']>0 && $level['dsc_ry_yeji_open']==1){
            $tiaojian3=get_dq_td_yeji($user_id)>=$level['dsc_ry_yeji'];
        }
        if ($level['market_num']>0 && $level['num']>0 && $level['num_level_id']>0 && $level['update_open']==1){
            $tiaojian4=get_rail_tiaojian($user_id,$level);
        }
        if (($tiaojian1 && $tiaojian2 && $tiaojian3 && $tiaojian4) && $level['level_id']>$user['level']){
            $level_id=$level['level_id'];
        }
    }
    return $level_id;
}
/**
 * 判断会员是否可以拿某个级别的奖励
 * @param int $user_id 会员id
 * @param int $level_id user_level表id
 */
function can_level_jl($user_id,$level_id){
    $level=UserLevel::find($level_id);
    $user=Users::find($user_id);
    $tiaojian1=$tiaojian2=$tiaojian3=$tiaojian4=true;
    if ($level['fh_lj_ry_yeji']>0 && $level['fh_lj_ry_open']==1){
        $tiaojian1=$user['lj_ry_yeji']>=$level['fh_lj_ry_yeji'];
    }
    if ($level['fh_td_ry_yeji']>0 && $level['fh_td_ry_yeji_open']==1){
        $tiaojian2=$user['td_ry_yeji']>=$level['fh_td_ry_yeji'];
    }
    if ($level['fh_dsc_ry_yeji']>0 && $level['fh_dsc_ry_yeji_open']==1){
        $tiaojian3=get_dq_td_yeji($user_id)>=$level['fh_dsc_ry_yeji'];
    }
    if ($level['fh_market_num']>0 && $level['fh_num']>0 && $level['fh_num_level_id']>0 && $level['fh_update_open']==1){
        $tiaojian4=get_rail_tiaojian($user_id,$level,2);
    }
    if ($tiaojian1 && $tiaojian2 && $tiaojian3 && $tiaojian4){
        return true;
    }
    return false;
}
/**
 * 判断会员几条线是否每条线达到条件
 * @param $user_id
 * @param $level
 */
function get_rail_tiaojian($user_id,$level,$type=1){
    //先判断是否够几条线
    $zt_where[]=['reid','=',$user_id];
    $zt_count=Db::name('users')->where($zt_where)->count();
    if ($zt_count<$level['market_num']&&$type==1){
        return false;
    }
    if ($zt_count<$level['fh_market_num']&&$type==2){
        return false;
    }
    //看直推伞下的
    $num=0;
    $zt_users_where[]=['reid','=',$user_id];
    $zt_users=Db::name('users')->where($zt_users_where)->column('user_id');
    foreach ($zt_users as $val){
        $ids=get_td_ids($val);
        //把当前会员也添加进去
        $ids[]=$val;
        if ($ids){
            $where[]=['user_id','in',$ids];
            $where[]=['level','>=',$level['num_level_id']];
            $count=Db::name('users')->where($where)->count();
            unset($where);
            if ($count>=$level['num']){
                $num++;
            }
        }
    }
    if ($num>=$level['market_num']){
        return true;
    }else{
        return false;
    }
}
/**
 * 获取用户小区ids
 * @param string $user_id 用户id
 * @param string $field 统计字段
 */
function get_xq_td_ids($user_id,$field='day_ry_yeji+day_td_ry_yeji'){
    $list=Db::name('users')->where('reid',$user_id)
        ->column("($field)",'user_id');
    if (empty($list)){
        return [];
    }
    //至少要2条线
    if (count($list)<=1){
        return [];
    }
    //大区id
    $daqu_id=array_search(max($list),$list);
    //删除大区 剩余的为小区
    unset($list[$daqu_id]);
    return array_keys($list);
}
/**
 * 获取用户剔除后的小区业绩
 * @param $user_id string 用户id
 */
function get_xq_td_yeji($user_id){
    $list=Db::name('users')->where('reid',$user_id)
        ->column('(td_ry_yeji+lj_ry_yeji)','user_id');
    if (empty($list)){
        return 0;
    }
    //至少要2条线
    if (count($list)<=1){
        return 0;
    }
    //大区id
    $daqu_id=array_search(max($list),$list);
    //删除大区 剩余的为小区
    unset($list[$daqu_id]);
    $xiaoqu_yeji=0;
    foreach ($list as $val){
        $xiaoqu_yeji+=$val;
    }
    return $xiaoqu_yeji;
}
/**
 * 获取用户大区业绩
 * @param $user_id string 用户id
 */
function get_dq_td_yeji($user_id){
    $list=Db::name('users')->where('reid',$user_id)
        ->column('(td_ry_yeji+lj_ry_yeji)','user_id');
    if (empty($list)){
        return 0;
    }
//    if (count($list)<=1){
//        return 0;
//    }
    //大区id
    $daqu_id=array_search(max($list),$list);
    return $list[$daqu_id];
}

if (!function_exists('dd')) {
    function dd($content)
    {
        echo '<pre>';
        exit(var_dump($content));
    }
}

function cdnurl($url, $domain = false)
{
    if(!$url) return '';
    $full_url = '';

    if($domain){
        $full_url .= \think\facade\Request::domain(true);
    }

    if(substr($url, 0, 8) != '/addons/'){
        $full_url .= config('site.cdnurl') . $url;
    }

    return $full_url;
}